package com.isoft.c2team3service2.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.isoft.c2team3service2.entity.*;
import com.isoft.c2team3service2.mapper.MainConcertsMapper;
import com.isoft.c2team3service2.mapper.RelatedToursMapper;
import com.isoft.c2team3service2.service.MainConcertsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import static com.isoft.c2team3service2.util.RedisConstants.ARTIST_SHOW;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 蓝莓
 * @since 2025-09-12
 */
@Service
public class MainConcertsServiceImpl extends ServiceImpl<MainConcertsMapper, MainConcerts> implements MainConcertsService {

    @Autowired
    private MainConcertsMapper mainMapper;

    @Autowired
    private RelatedToursMapper relatedToursMapper;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

//    # 选择淘汰策略（二选一）：
//   1. allkeys-lru：所有键中，淘汰最近最少使用（LRU）的键
//   2. volatile-lru：仅淘汰设置了过期时间且最近最少使用的键
//    maxmemory-policy allkeys-lru
    @Override
    public List<MainConcerts> getInformation() {
        List<MainConcerts> mainConcerts = mainMapper.selectList(new QueryWrapper<>());

        mainConcerts.forEach(m -> {
            List<RelatedTours> relatedList = relatedToursMapper.selectList(
                    new QueryWrapper<RelatedTours>().eq("concert_id", m.getId())
            );

            ConcertDetailDTO dto = new ConcertDetailDTO();
            dto.setId(m.getId());
            dto.setArtist(m.getArtist());
            dto.setName(m.getName());
            dto.setGenre(m.getGenre());
            dto.setLanguage(m.getLanguage());
            dto.setCountry(m.getCountry());
            dto.setCity(m.getCity());
            dto.setDate(m.getDate());
            dto.setTime(m.getTime());
            dto.setTicketStatus(m.getTicketStatus());
            dto.setImage(m.getImage());
            dto.setVenue(m.getVenue());
            dto.setVenueAddress(m.getVenueAddress());
            dto.setVenueIntro(m.getVenueIntro());
            dto.setVenueMap(m.getVenueMap());
            dto.setDescription(m.getDescription());

            List<RelatedTourDTO> schedule = relatedList.stream().map(rt -> {
                RelatedTourDTO rtd = new RelatedTourDTO();
                rtd.setDate(rt.getDate());
                rtd.setCity(rt.getCity());
                rtd.setCountry(rt.getCountry());
                rtd.setVenue(rt.getVenue());
                rtd.setStatus(rt.getStatus());
                return rtd;
            }).toList();

            dto.setRelatedTourSchedule(schedule);

            try {
                String key = ARTIST_SHOW + ":" + m.getArtist();
                String jsonValue = objectMapper.writeValueAsString(dto);
                stringRedisTemplate.opsForValue().set(key, jsonValue);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        });

        return mainConcerts;
    }

@Override
public List<ConcertDetailDTO> search(ConcertsDTO concertsDTO) {
    List<ConcertDetailDTO> result = new ArrayList<>();

    try {
        // 根据艺人名称模糊查询
        if (StrUtil.isNotBlank(concertsDTO.getArtistName())) {
            Set<String> keys = stringRedisTemplate.keys(ARTIST_SHOW + ":*" + concertsDTO.getArtistName() );
//            Set<String> keys = stringRedisTemplate.keys(ARTIST_SHOW + ":*" + concertDetailDTO.getArtist() + "*");
            if (keys != null && !keys.isEmpty()) {
                List<String> values = stringRedisTemplate.opsForValue().multiGet(keys);
                if (values != null) {
                    for (String value : values) {
                        if (value != null) {
                            ConcertDetailDTO dto = objectMapper.readValue(value, ConcertDetailDTO.class);
                            result.add(dto);
                        }
                    }
                }
            }
        }
        // 根据国家查询
        else if (StrUtil.isNotBlank(concertsDTO.getCountry())) {
            Collection<String> allKeys = stringRedisTemplate.keys(ARTIST_SHOW + ":*");
            if (allKeys != null) {
                List<String> values = stringRedisTemplate.opsForValue().multiGet(allKeys);
                if (values != null) {
                    for (String value : values) {
                        if (value != null) {
                            ConcertDetailDTO dto = objectMapper.readValue(value, ConcertDetailDTO.class);
                            // 检查主要演出或相关巡演中是否有匹配的国家
                            boolean match = dto.getCountry().equals(concertsDTO.getCountry()) ||
                                    dto.getRelatedTourSchedule().stream()
                                            .anyMatch(rt -> rt.getCountry().equals(concertsDTO.getCountry()));
                            if (match) {
                                result.add(dto);
                            }
                        }
                    }
                }
            }
        }
        // 根据音乐类型查询
        else if (StrUtil.isNotBlank(concertsDTO.getMusicType())) {
            Collection<String> allKeys = stringRedisTemplate.keys(ARTIST_SHOW + ":*");
            if (allKeys != null) {
                List<String> values = stringRedisTemplate.opsForValue().multiGet(allKeys);
                if (values != null) {
                    for (String value : values) {
                        if (value != null) {
                            ConcertDetailDTO dto = objectMapper.readValue(value, ConcertDetailDTO.class);
                            if (dto.getGenre().equals(concertsDTO.getMusicType())) {
                                result.add(dto);
                            }
                        }
                    }
                }
            }
        }
        // 根据时间范围查询
        else if (StrUtil.isNotBlank(concertsDTO.getStartTime())) {
            Collection<String> allKeys = stringRedisTemplate.keys(ARTIST_SHOW + ":*");
            if (allKeys != null) {
                List<String> values = stringRedisTemplate.opsForValue().multiGet(allKeys);
                if (values != null) {
                    for (String value : values) {
                        if (value != null) {
                            ConcertDetailDTO dto = objectMapper.readValue(value, ConcertDetailDTO.class);
//                            if (dto.getGenre().equals(concertsDTO.getStartTime())) {
//                                result.add(dto);
//                            }
                            /**
                             * 1个月内   "month"	筛选未来1个月内的巡演
                             * 3个月内	"quarter"	筛选未来3个月内的巡演
                             * 半年内	"halfYear"	筛选未来6个月内的巡演
                             * 1年内	    "year"   筛选未来1年内的巡演
                             */
                            if ("month".equals(concertsDTO.getStartTime())) {
                                if (dto.getDate().isAfter(LocalDate.now().plusMonths(1))) {
                                    result.add(dto);
                                }
                                if ("quarter".equals(concertsDTO.getStartTime())) {
                                    if (dto.getDate().isAfter(LocalDate.now().plusMonths(3))) {
                                        result.add(dto);
                                    }
                                }
                                if ("halfYear".equals(concertsDTO.getStartTime())) {
                                    if (dto.getDate().isAfter(LocalDate.now().plusMonths(6))) {
                                        result.add(dto);
                                    }
                                }
                                if ("year".equals(concertsDTO.getStartTime())) {
                                    if (dto.getDate().isAfter(LocalDate.now().plusYears(1))) {
                                        result.add(dto);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }

    return result;
}
}
